
var {Options} = require('selenium-webdriver/chrome'),
    webdriver=require('selenium-webdriver/lib/webdriver'),
    {Builder,By,until}=require('selenium-webdriver'),
    config=require('./config.js'),
    text=require('./text.js'),
    https = require('https'),
    fs = require('fs'),
    clipboardy = require('clipboardy'),
    driver=new Builder().withCapabilities(
        Options.chrome().setPageLoadStrategy('none')
    ).build()


async function fanyi(arr){
    var str=arr.join("\n")
    await driver.get('https://fanyi.baidu.com/#en/zh/'+encodeURI(str))
    var ele=driver.wait(until.elementLocated(By.id('translate-button')))
    ele.click()
    await sleep(5e3)
    ele= await driver.findElement(By.xpath('//div[@class="output-mod ordinary-wrap"]/div[@class="output-bd"]'))
    var ans=await ele.getAttribute('innerText')
    return ans.trim().split(/\n+/g)
}
async function sleep(duration){
    return new Promise(resolve => setTimeout(resolve, duration))
}

async function trans(file){
    console.log(file)
    var str=fs.readFileSync(file,{encoding:'utf8'})
    var ans=str.split("\n\n").slice(1).map(v=>{
        var [idx,dur,...arr]=v.split("\n")
        return [idx,dur,arr.join(" ").replace(/&gt;&gt;[^:]+:/g,'')]
    })
    var before=ans.map(v=>v[2])
    var len=Math.ceil(before.length/40)
    var after=[],count=0
    for(var i =1;i<=len;i++){
        after=after.concat(await fanyi(before.slice((i-1)*40,i*40)))
    }

    for( var idx in ans){
        ans[idx].push(after[idx])
    }
    return "WEBVTT\n\n"+ans.map(v=>v.join("\n")).join("\n\n")
}

async function grepfile(){
    var process = require('child_process');
    return new Promise((resolve,reject)=>{
        process.exec('cd '+config.root+' && find -name "*web_vtt"',function (error, stdout, stderr) {
            if (error !== null) {
                reject(error)
            }else{
                resolve(stdout.replace(/\.\//g,config.root).split("\n"))
            }
        });
    })
    
}

async function main(){
    files=await grepfile()
    for(item of files){
        if(item.trim().length===0)continue
        var ansfile=item.replace('web_vtt','webvtt')
        if(fs.existsSync(ansfile))continue
        var detail=await trans(item)
        fs.writeFile(ansfile, detail, function(err) {
            if (err) throw err;
        })
    }
    driver.quit()
}
main()
